package com.kooison.idevice4u.crawler;

import java.net.URL;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Properties;
import java.util.logging.Logger;

import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;

import com.kooison.idevice4u.bean.ProductDetail;
import com.kooison.idevice4u.utils.PropertyLoader;

/**
 * Crawler for "Buy iPhone 4S at the Apple Online Store"
 * 
 */
public class AppleStoreCrawler {
	enum PAGE_TYPE { SELECT, ITEM, RETAIL }
	
	private final Logger logger = Logger.getLogger(this.getClass().getName());
	private ArrayList<ProductDetail> list = new ArrayList<ProductDetail>();
	private ProductDetail bean = null;
	private String xPathForButton = null;
	private String xPathForProductInfo = null;

	private boolean isAvailable = false;
	
	public boolean isAvailable() {
		return isAvailable;
	}

	public void setAvailable(boolean isAvailable) {
		this.isAvailable = isAvailable;
	}
	
	public AppleStoreCrawler(String product, String region) throws Exception {
		String path = null;
		Properties prop = PropertyLoader.loadProperties("product_config.properties");

		// select page
		path = (String) prop.get(product + ".orderPage.url");
		path = MessageFormat.format(path, new Object[] { region });
		
		xPathForButton = (String) prop.get(product + ".button.xpath");
		xPathForProductInfo = (String) prop.get(product + ".info.xpath");
		
		if (path == null) {
			throw new Exception("Incorrect product or region");
		}
		
		bean = new ProductDetail(product, region, null, null, path, ProductDetail.PAGE_TYPE.SELECT);
	}

	public ArrayList<ProductDetail> getResultList() throws Exception {
		URL url = new URL(bean.getUrl());

		TagNode root = new HtmlCleaner().clean(url);
		
		// find the button
		for (Object anchorObj : root.evaluateXPath(xPathForButton)) {
			TagNode anchorNode = (TagNode) anchorObj;
			logger.info("Node:" + anchorNode.getText().toString().trim().replaceAll("\\s+", "-"));
			ProductDetail info = new ProductDetail(bean.getProduct(), bean.getRegion());

			// url
			TagNode a = anchorNode.findElementHavingAttribute("href", true);
			if (a != null) {
				info.setUrl("http://" + url.getHost() + a.getAttributeByName("href"));
			} else {
				info.setUrl("Link not exist");
			}

			// find product info
			for (Object spanObj : anchorNode.evaluateXPath(xPathForProductInfo)) {
				TagNode spanNode = (TagNode) spanObj;

				// size
				if ("title".equals(spanNode.getAttributeByName("class"))) {
					String size = spanNode.getText().toString().trim();
					size = size.substring(0, size.length()-1);
					info.setSize(size);
				}

				// color
				if ("color".equals(spanNode.getAttributeByName("class"))) {
					info.setColor(spanNode.getText().toString().trim());
				}

				// price
				if ("current_price".equals(spanNode.getAttributeByName("class"))) {
					info.setPrice(spanNode.getText().toString().trim());
				}

				// shipping
				if ("shipping".equals(spanNode.getAttributeByName("class"))) {
					String shipping = spanNode.getText().toString().trim();
					if (shipping.indexOf("unavailable") < 0) {
						info.setAvailable(true);
						bean.setAvailable(true);
						this.setAvailable(true);
					}
				}
			}
			logger.info(info.toString());
			list.add(info);
		}
		list.add(bean);
		return list;
	}
}
